import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_application_1/global.dart';
import 'package:flutter_application_1/utils/source_utils.dart';

class Splash extends StatefulWidget {
  @override
  _SplashState createState() => _SplashState();
}

class _SplashState extends State<Splash> {
  int _waitTime = 3;

  late Timer _timer;

  // 下一页
  _next() {
    _timer.cancel();
    Global.routerUtils.navigateTo(
      context,
      Global.routeMap.root,
      replace: true,
    );
  }

  // 设置倒计时
  _countdown() {
    _timer = Timer(
      Duration(seconds: 1),
      () {
        setState(() {
          _waitTime--;
          if (_waitTime <= 0) {
            _next();
          } else {
            _countdown();
          }
        });
      },
    );
  }

  Widget _textBuilder(String text) {
    return Text(
      text,
      style: TextStyle(
        color: Color.fromRGBO(255, 255, 255, 0.8),
        fontSize: 16,
        height: 1,
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    // 开始倒计时
    _countdown();
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: WillPopScope(
        onWillPop: () => Future.value(false),
        child: Stack(
          fit: StackFit.expand,
          children: [
            Image.asset(
              ImageUtils.wrapAssets('splash.jpg'),
              fit: BoxFit.cover,
            ),
            Positioned(
              right: 30,
              bottom: 30,
              child: GestureDetector(
                onTap: () {
                  _next();
                },
                child: Container(
                  width: 90,
                  height: 35,
                  padding: EdgeInsets.symmetric(
                    horizontal: 10,
                  ),
                  decoration: BoxDecoration(
                    color: Color.fromRGBO(0, 0, 0, 0.5),
                    borderRadius: BorderRadius.circular(40),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      _textBuilder('$_waitTime'),
                      Container(
                        width: 1,
                        height: 15,
                        color: Color.fromRGBO(255, 255, 255, 0.8),
                      ),
                      _textBuilder('跳过'),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
